package com.cold.demo.jxls;

import org.jxls.builder.xls.AreaCommand;
import org.jxls.builder.xls.XlsCommentAreaBuilder;
import org.jxls.command.*;
import org.jxls.common.Context;
import org.jxls.expression.JexlExpressionEvaluator;
import org.jxls.transform.Transformer;
import org.jxls.util.JxlsHelper;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JxlsUtil {

    static {
        //添加自定义指令（可覆盖jxls原指令）
        XlsCommentAreaBuilder.addCommandMapping(MergeCommand.COMMAND_NAME, MergeCommand.class);
        XlsCommentAreaBuilder.addCommandMapping(ImageCommand.COMMAND_NAME, ImageCommand.class);
        XlsCommentAreaBuilder.addCommandMapping(EachCommand.COMMAND_NAME, EachCommand.class);
        XlsCommentAreaBuilder.addCommandMapping(IfCommand.COMMAND_NAME, IfCommand.class);
        XlsCommentAreaBuilder.addCommandMapping(AreaCommand.COMMAND_NAME, AreaCommand.class);
        XlsCommentAreaBuilder.addCommandMapping(GridCommand.COMMAND_NAME, GridCommand.class);
        XlsCommentAreaBuilder.addCommandMapping(UpdateCellCommand.COMMAND_NAME, UpdateCellCommand.class);
    }


    public static void exportExcel(InputStream is, OutputStream os, Map<String, Object> model) throws IOException {
        Context context = new Context();
        if (model != null) {
            for (String key : model.keySet()) {
                context.putVar(key, model.get(key));
            }
        }
        JxlsHelper              jxlsHelper  = JxlsHelper.getInstance();
        Transformer             transformer = jxlsHelper.createTransformer(is, os);
        JexlExpressionEvaluator evaluator   = (JexlExpressionEvaluator) transformer.getTransformationConfig().getExpressionEvaluator();
        Map<String, Object>     funcs       = new HashMap<>();
        funcs.put("utils", new JxlsUtil()); // 添加自定义功能
        evaluator.getJexlEngine().setFunctions(funcs);
        jxlsHelper.processTemplate(context, transformer);
    }

    public String dateFmt(Date date, String fmt) {
        if (date == null) {
            return null;
        }
        try {
            SimpleDateFormat dateFmt = new SimpleDateFormat(fmt);
            return dateFmt.format(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public Object ifElse(boolean b, Object o1, Object o2) {
        return b ? o1 : o2;
    }
}
